from flask import Blueprint, request, jsonify, send_file
from services.imageService import imageService
image_bp = Blueprint("image",__name__)
# 配置上传目录
UPLOAD_FOLDER = 'uploads'

# 初始化 ImageService
image_service = imageService(UPLOAD_FOLDER)


@image_bp.route('/convert', methods=['POST'])
def convert():
    try:
        # 检查是否有文件上传
        if 'image' not in request.files:
            return 'No image uploaded', 400

        image_file = request.files['image']
        size = int(request.form.get('size', 32))  # 默认尺寸为 32x32

        # 验证文件
        image_service.validate_file(image_file)

        # 调用业务层进行转换
        ico_file = image_service.convert_to_ico(image_file, size)

        # 返回 ICO 文件
        return send_file(
            ico_file,
            mimetype='image/x-icon',
            as_attachment=True,
            download_name='favicon.ico'
        )
    except ValueError as ve:
        return str(ve), 400
    except Exception as e:
        return f'转换失败: {str(e)}', 500